//
//  ViewController.swift
//  TestMeeting
//
//  Created by json on 2020/12/25.
//

import UIKit
import SwiftSignalRClient
import WebRTC

class ViewController: UIViewController {

    private let serverUrl = ""
    private var signalConnection: HubConnection?
    private var signalConnectionDelegate: HubConnectionDelegate?
    private var webRTCClient: WebRTCClient?
    private let config = Config.default
    private var localVideo : RTCMTLVideoView?
    override func viewDidLoad() {
        super.viewDidLoad()
        
        webRTCClient = WebRTCClient(iceServers: self.config.webRTCIceServers)
        webRTCClient?.delegate = self
        self.signalConnectionDelegate = SignalConnectionDelegate(controller: self)
        self.signalConnection = HubConnectionBuilder(url: URL(string: "http://192.168.101.11:8050/signalling")!)
            .withLogging(minLogLevel: .debug)
            .withAutoReconnect()
            .withHubConnectionDelegate(delegate: self.signalConnectionDelegate!)
            .build()
        self.signalConnection?.start()
        self.signalConnection?.on(method: "UserCreateRoom", callback: { (data: String) in
            print("创建房间成功 \(data)")
        })
        self.signalConnection?.on(method: "UserJoinRoom", callback: { (data: String) in
            
        })
        self.signalConnection?.on(method: "ExitRoom", callback: { (data: String) in
            
        })
        self.signalConnection?.on(method: "CloseRoom", callback: { (data: String) in
            
        })
        self.signalConnection?.on(method: "Answer", callback: { (data: String) in
            
        })
        self.initSubView()
    }

    func initSubView() {
        let screenHeight = UIScreen.main.bounds.height
        let screenWidth  = UIScreen.main.bounds.width
        let btn = UIButton(frame: CGRect(x: 0, y:screenHeight - 40 , width: screenWidth / 4, height: 40))
        btn.setTitle("create", for: UIControl.State.normal)
        self.view.addSubview(btn)
        btn.setTitleColor(UIColor.white, for: UIControl.State.normal)
        btn.addTarget(self, action: #selector(creatRoom), for: UIControl.Event.touchUpInside)
        
        localVideo = RTCMTLVideoView(frame: CGRect.init(x: 0, y: 0, width: screenWidth / 2, height: screenWidth / 2))
        self.view.addSubview(localVideo!)
    }
    @objc func creatRoom() {
        let t = Test()
        t.sdpDescription = "fffffffffff"
        self.signalConnection!.invoke(method: "CreateRoom", t) { (e:Error?) in
            
        }
//        self.signalConnection?.invoke(method: "CreateRoom",t, invocationDidComplete: { (error: Error?) in
//
//        })

        // 生成sdp 创建房间
        self.webRTCClient?.offer(completion: { (sdp) in
//            let sdpString = "{'type':'3', 'sdpDescription':\(sdp.sdp)}"
//            self.signalConnection?.invoke(method: "CreateRoom",sdpString, invocationDidComplete: { (error: Error?) in
//
//            })
        })
//       /// 本地local 显示
//        self.webRTCClient?.startCaptureLocalVideo(renderer: self.localVideo!)
    }
    
}
class Test : Encodable{
    public var type: Int = 3
    public var sdpDescription: String?
    
}
class SignalConnectionDelegate: HubConnectionDelegate {
    
    init(controller: ViewController) {
        self.controller = controller
    }
    func connectionDidOpen(hubConnection: HubConnection) {
        print("didOpen")
    }
    
    func connectionDidFailToOpen(error: Error) {
        print("didFail")
    }
    
    func connectionDidClose(error: Error?) {
        print("didClose")
    }
    
    weak var controller : ViewController?
    
}

extension ViewController : WebRTCClientDelegate {
    func webRTCClient(_ client: WebRTCClient, didDiscoverLocalCandidate candidate: RTCIceCandidate) {
        print("didDiscoverLocalCandidate")
    }
    
    func webRTCClient(_ client: WebRTCClient, didChangeConnectionState state: RTCIceConnectionState) {
        print("didChangeConnectionState")
    }
    
    func webRTCClient(_ client: WebRTCClient, didReceiveData data: Data) {
        print("didReceiveData")
    }
    
}
